package com.cn.transfer.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.InspectionData;
import com.cn.transfer.common.entity.jiandaoyun.Order0111;
import com.cn.transfer.common.entity.jiandaoyun.SAPPurchaseOrder;
import com.cn.transfer.common.entity.jiandaoyun.User;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.cn.transfer.handle.impl.purchase.community.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author: weidian
 * @date: 2024/7/19 11:27
 * @Description: 采购订单子表单数量修改
 */
@RestController
@Slf4j
public class StockQuantity {

    private final ResourceLoader resourceLoader;

    private static final String SECRET = "ERsdfSFWERDSFDSd";
    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";
    private static final String DATA_DELETE = "data_remove";

    public StockQuantity(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    private static final int CORE_POOL_SIZE = 20;         // 核心线程数
    private static final int MAXIMUM_POOL_SIZE = 200;     // 最大线程数
    private static final long KEEP_ALIVE_TIME = 60L;      // 空闲线程存活时间
    private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // 存活时间单位
    private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(200); // 任务队列

    // 创建自定义线程池
    private static ExecutorService threadPool = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAXIMUM_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TIME_UNIT,
            WORK_QUEUE,
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
    );

    @PostMapping("/StockQuantity")
    public String callback(@RequestParam("nonce") String nonce,
                           @RequestParam("timestamp") String timestamp,
                           @RequestHeader("x-jdy-signature") String signature,
                           @RequestBody String payload) {
        //log.info("存货申请=====" + payload);
        if (!validateSignature(nonce, payload, timestamp, signature)) {
            return "fail";
        }
        // 在这里处理消息
        threadPool.submit(() -> handleData(payload));

        return "success";
    }
    private boolean validateSignature(String nonce, String payload, String timestamp, String signature) {
        String calculatedSignature = getSignature(nonce, payload, StockQuantity.SECRET, timestamp);
        return calculatedSignature.equals(signature);
    }

    private String getSignature(String nonce, String payload, String secret, String timestamp) {
        return DigestUtils.sha1Hex(nonce + ":" + payload + ":" + secret + ":" + timestamp);
    }
    private void handleData(String payload) {
        // 在这里处理推送来的数据
        JSONObject payloadJSON = JSONUtil.parseObj(payload);
        String op = payloadJSON.getStr("op");
        String data = payloadJSON.getStr("data");

        if (DATA_CREATE.equals(op)) {
            create(data);
        }
    }
    private void create(String data) {

        Header[] headers = ConnmeUtils.createHeaders();
        InspectionData inspectionData = JSONUtil.toBean(data, InspectionData.class);
        if (inspectionData.getInspection_result().equals("NG")){
            return;
        }
        if (inspectionData.getInspection_place().equals("公司仓库")){
            Map<String, Object> parameterCx = new HashMap<>();
            parameterCx.put("app_id", "6690c7633df0f4b90b4ef551");
            parameterCx.put("entry_id", "669df675b02f2a74e35ca2f9");
            HashMap<String,String> hashMap=new HashMap<>();
            hashMap.put("_widget_1721628277543", inspectionData.getPurchasing_no());
            hashMap.put("_widget_1721628277558", inspectionData.getPurchasing_hang());
            List<Order0111> order0111s = PurchaseCommunity.
                    queryBased(parameterCx, headers,hashMap, Order0111.class);
                order0111s.get(0).set_widget_1721978605698(inspectionData.getTotal_qty()+ order0111s.get(0).get_widget_1721978605698());
            Updatck(headers, order0111s);
            return;
        } else {
            Map<String, Object> parameterCx = new HashMap<>();
            parameterCx.put("app_id", "6690c7633df0f4b90b4ef551");
            parameterCx.put("entry_id", "669df675b02f2a74e35ca2f9");
            HashMap<String,String> hashMap=new HashMap<>();
            hashMap.put("_widget_1721628277543", inspectionData.getPurchasing_no());
            hashMap.put("_widget_1721628277558", inspectionData.getPurchasing_hang());
            List<Order0111> order0111s = PurchaseCommunity.
                    queryBased(parameterCx, headers, hashMap, Order0111.class);
            order0111s.get(0).set_widget_1721632911791(inspectionData.getTotal_qty()+ order0111s.get(0).get_widget_1721632911791());
            Updatck(headers, order0111s);
        }

//        Map<String, Object> parameterCx = new HashMap<>();
//        parameterCx.put("app_id", "6690c7633df0f4b90b4ef551");
//        parameterCx.put("entry_id", "6690c891b1ffef3310d1b90d");
//
//        List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(parameterCx, headers, inspectionData.getPurchasing_no(), "_widget_1720764561287", SAPPurchaseOrder.class);
//
//        for (SAPPurchaseOrder.Subform subform : sapPurchaseOrders.get(0).get_widget_1720764671480()) {
//            if (subform.get_widget_1720764671534().equals(inspectionData.getPurchasing_hang())){
//                if ( subform.get_widget_1721269068900()==null){
//                    subform.set_widget_1721269068900((double) inspectionData.getTotal_qty());
//                }else {
//                    subform.set_widget_1721269068900(subform.get_widget_1721269068900()+inspectionData.getTotal_qty());
//                }
//                break;
//            }
//        }
//        Map<String, Object> parameterInster = new HashMap<>();
//        parameterInster.put("app_id", "6690c7633df0f4b90b4ef551");
//        parameterInster.put("entry_id", "6690c891b1ffef3310d1b90d");
//        parameterInster.put("is_start_trigger", "true");
//        parameterInster.put("data_id", sapPurchaseOrders.get(0).get_id());
//        sapPurchaseOrders.get(0).set_widget_1720764561290(null);
//        sapPurchaseOrders.get(0).set_widget_1720764561295(null);
//        sapPurchaseOrders.get(0).set_widget_1720764561297(null);
//        sapPurchaseOrders.get(0).set_widget_1720764561300(null);
//        for (int i = 0; i < sapPurchaseOrders.get(0).get_widget_1720764671480().size(); i++) {
//            User user1 = JSONUtil.toBean(sapPurchaseOrders.get(0).get_widget_1720764671480().get(i).get_widget_1720764671513(), User.class);
//            User user2 = JSONUtil.toBean(sapPurchaseOrders.get(0).get_widget_1720764671480().get(i).get_widget_1720764671514(), User.class);
//            sapPurchaseOrders.get(0).get_widget_1720764671480().get(i).set_widget_1720764671513(user1.getUsername());
//            sapPurchaseOrders.get(0).get_widget_1720764671480().get(i).set_widget_1720764671514(user2.getUsername());
//        }
//        sapPurchaseOrders.get(0).set_id(null);
//        parameterInster.put("data",ConnmeUtils.convertEntityToMapNull(sapPurchaseOrders.get(0)));
//        String jsonSale = JSONUtil.toJsonStr(parameterInster);
//        log.info("修改采购订单收货数量"+jsonSale);
//        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
    }

    private void Updatck(Header[] headers, List<Order0111> order0111s) {
        Map<String, Object> parameterInster002 = new HashMap<>();
        parameterInster002.put("app_id", "6690c7633df0f4b90b4ef551");
        parameterInster002.put("entry_id", "669df675b02f2a74e35ca2f9");
        parameterInster002.put("is_start_trigger", "true");
        parameterInster002.put("data_id", order0111s.get(0).get_id());
        order0111s.get(0).set_id(null);
        parameterInster002.put("data", ConnmeUtils.convertEntityToMapNull(order0111s.get(0)));
        String jsonSale = JSONUtil.toJsonStr(parameterInster002);
        log.info("修改采购改工厂数"+jsonSale);
        JSONObject entries = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
    }
}
